<template>
    <div class="customRichText">
        <div id="toolbar-container"></div>
        <div id="editor-container"></div>
    </div>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, reactive, watch } from "vue";
import "@wangeditor/editor/dist/css/style.css";
import { createEditor, createToolbar, IEditorConfig, IDomEditor } from "@wangeditor/editor";
export default defineComponent({
    emits: ["update:value"],
    props: {
        value: {
            type: String,
            default: "",
        },
    },
    setup(props, context) {
        const editorConfig: Partial<IEditorConfig> = {
            MENU_CONF: {
                uploadImage: {
                    server: process.env.VUE_APP_UPLOAD,
                    withCredentials: true,
                    fieldName: "file",
                    // 自定义插入图片
                    customInsert(res: any, insertFn: (url: string, alt?: string, href?: string) => void) {
                        insertFn(`${process.env.VUE_APP_BASEURL}${res.data}`);
                    },
                },
            },
        };
        editorConfig.placeholder = "请输入内容";
        editorConfig.onChange = (editor: IDomEditor) => {
            // 当编辑器选区、内容变化时，即触发
            // console.log("content", editor.children);
            // console.log("html", editor.getHtml());
            state.innerValue = editor.getHtml();
        };

        let editor: IDomEditor | null = null;
        onMounted(() => {
            const text = props.value; // text 内容
            // 创建编辑器
            editor = createEditor({
                selector: "#editor-container",
                config: editorConfig,
                mode: "default", // 或 'simple' 参考下文
                html: text,
            });
            // 创建工具栏
            const toolbar = createToolbar({
                editor,
                selector: "#toolbar-container",
                mode: "simple", // 或 'simple' 参考下文
            });
        });
        watch(
            () => props.value,
            newV => {
                // 全选并删除
                editor?.select([]);
                editor?.deleteFragment();
                // 1.2 插入内容
                editor?.dangerouslyInsertHtml(newV);
            }
        );
        const state = reactive({
            innerValue: computed({
                set: val => {
                    context.emit("update:value", val);
                },
                get: () => editor?.getHtml(),
            }),
        });
    },
});
</script>

<style scoped lang="scss">
.customRichText {
    display: flex;
    flex-direction: column;
    height: 100%;
    #editor-container {
        flex-grow: 1;
    }
}
</style>
